import React, { useState, useEffect } from 'react';
import {
  Card,
  Button,
  Tag,
  Space,
  Typography,
  Row,
  Col,
  Divider,
  Modal,
  Form,
  Select,
  message,
  Spin,
  Avatar,
} from 'antd';
import {
  StarOutlined,
  UserOutlined,
  CalendarOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import { useParams, useNavigate } from 'react-router-dom';
import { getRequestDetail, fillRequest, closeRequest, downloadTorrent } from '../../api/request';
import { getTorrents } from '../../api/torrent';
import { getCurrentUser } from '../../api/user';
import { Request, Torrent, User } from '../../types';
import { formatDateTime, formatSize } from '../../utils/format';

const { Title, Text, Paragraph } = Typography;
const { Option } = Select;

const RequestDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [request, setRequest] = useState<Request | null>(null);
  const [currentUser, setCurrentUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);
  const [fillModalVisible, setFillModalVisible] = useState(false);
  const [torrents, setTorrents] = useState<Torrent[]>([]);
  const [form] = Form.useForm();
  const [submitting, setSubmitting] = useState(false);

  useEffect(() => {
    if (id) {
      fetchRequestDetail();
      fetchCurrentUser();
    }
  }, [id]);

  const fetchRequestDetail = async () => {
    try {
      setLoading(true);
      const response = await getRequestDetail(Number(id));
      if (response.code === 200) {
        setRequest(response.data);
      }
    } catch (error) {
      console.error('获取求种详情失败:', error);
      message.error('获取求种详情失败');
    } finally {
      setLoading(false);
    }
  };

  const fetchCurrentUser = async () => {
    try {
      const response = await getCurrentUser();
      if (response.code === 200) {
        setCurrentUser(response.data);
      }
    } catch (error) {
      console.error('获取当前用户失败:', error);
    }
  };

  const fetchTorrents = async () => {
    try {
      console.log('=== 获取种子列表 ===');
      console.log('request:', request);
      console.log('categoryId:', request?.categoryId);
      console.log('categoryName:', request?.categoryName);
      
      // 根据求种分类获取相关种子
      const queryParams = {
        page: 1,
        size: 100,
        // 使用分类名称而不是ID，因为种子接口期望的是分类名称
        category: request?.categoryName || undefined,
      };
      
      console.log('查询参数:', queryParams);
      
      const response = await getTorrents(queryParams);
      console.log('种子列表响应:', response);
      
      if (response.code === 200) {
        console.log('获取到种子数量:', response.data.records.length);
        console.log('种子列表:', response.data.records);
        setTorrents(response.data.records.filter(torrent => 
          // 只显示已通过审核的种子
          torrent.status === 1
        ));
      } else {
        console.error('获取种子失败:', response.message);
        message.error(response.message || '获取种子列表失败');
      }
    } catch (error) {
      console.error('获取种子列表失败:', error);
      message.error('获取种子列表失败');
    }
  };

  const handleFill = () => {
    if (!currentUser) {
      message.error('请先登录');
      return;
    }
    if (currentUser.id === request?.userId) {
      message.error('不能完成自己发起的求种');
      return;
    }
    setFillModalVisible(true);
    fetchTorrents();
  };

  const handleFillRequest = async (values: { torrentId: number }) => {
    try {
      setSubmitting(true);
      const response = await fillRequest(Number(id), values.torrentId);
      console.log('完成求种响应:', response);
      
      if (response.code === 200) {
        message.success('求种完成成功！');
        setFillModalVisible(false);
        fetchRequestDetail();
      } else {
        message.error(response.message || '完成求种失败');
      }
    } catch (error) {
      console.error('完成求种失败:', error);
      message.error('完成求种失败，请稍后重试');
    } finally {
      setSubmitting(false);
    }
  };

  const handleCloseRequest = async () => {
    try {
      const response = await closeRequest(Number(id));
      if (response.code === 200) {
        message.success('求种关闭成功！');
        fetchRequestDetail();
      }
    } catch (error) {
      console.error('关闭求种失败:', error);
      message.error('关闭求种失败，请稍后重试');
    }
  };

  const getStatusTag = (status: number) => {
    switch (status) {
      case 0:
        return <Tag color="processing">进行中</Tag>;
      case 1:
        return <Tag color="success">已完成</Tag>;
      case 2:
        return <Tag color="default">已关闭</Tag>;
      default:
        return <Tag>未知</Tag>;
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
      </div>
    );
  }

  if (!request) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text>求种不存在</Text>
      </div>
    );
  }

  return (
    <div>
      <Card>
        <Row gutter={24}>
          <Col span={16}>
            <Space direction="vertical" style={{ width: '100%' }}>
              <div>
                <Title level={2}>{request.title}</Title>
                <Space>
                  <Tag color="blue">{request.categoryName || '未分类'}</Tag>
                  {getStatusTag(request.status)}
                </Space>
              </div>

              <Divider />

              <div>
                <Title level={4}>求种描述</Title>
                <Paragraph>
                  {request.description || '暂无描述'}
                </Paragraph>
              </div>

              {request.status === 1 && request.filledBy && (
                <div>
                  <Title level={4}>完成信息</Title>
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <Text>完成者: {request.filledBy}</Text>
                    <Text>完成时间: {formatDateTime(request.filledAt || '')}</Text>
                    {request.torrentTitle && (
                      <>
                        <Divider />
                        <Title level={4}>种子信息</Title>
                        <Text>标题: {request.torrentTitle}</Text>
                        <Text>大小: {formatSize(request.torrentSize || 0)}</Text>
                        <Button 
                          type="primary" 
                          icon={<DownloadOutlined />}
                          onClick={async () => {
                            try {
                              await downloadTorrent(Number(id));
                              message.success('开始下载种子文件');
                            } catch (error) {
                              message.error('下载失败');
                            }
                          }}
                        >
                          下载种子
                        </Button>
                      </>
                    )}
                  </Space>
                </div>
              )}
            </Space>
          </Col>

          <Col span={8}>
            <Card title="求种信息" size="small">
              <Space direction="vertical" style={{ width: '100%' }}>
                <div>
                  <Text strong>悬赏魔力值</Text>
                  <div>
                    <Text style={{ fontSize: '24px', color: '#fa8c16' }}>
                      <StarOutlined /> {request.rewardPoints}
                    </Text>
                  </div>
                </div>

                <Divider />

                <div>
                  <Space>
                    <Avatar icon={<UserOutlined />} />
                    <div>
                      <div>发起者: {request.username}</div>
                      <Text type="secondary">
                        <CalendarOutlined /> {formatDateTime(request.createdAt)}
                      </Text>
                    </div>
                  </Space>
                </div>

                {request.status === 0 && currentUser && (
                  <div style={{ marginTop: 16 }}>
                    {currentUser.id !== request.userId ? (
                      <Button
                        type="primary"
                        block
                        icon={<CheckCircleOutlined />}
                        onClick={handleFill}
                      >
                        完成求种
                      </Button>
                    ) : (
                      <Button
                        danger
                        block
                        icon={<CloseCircleOutlined />}
                        onClick={handleCloseRequest}
                      >
                        关闭求种
                      </Button>
                    )}
                  </div>
                )}
              </Space>
            </Card>
          </Col>
        </Row>
      </Card>

      <Modal
        title="完成求种"
        open={fillModalVisible}
        onCancel={() => setFillModalVisible(false)}
        footer={null}
        width={600}
      >
        <Form
          form={form}
          onFinish={handleFillRequest}
          layout="vertical"
        >
          <Form.Item
            label="选择种子"
            name="torrentId"
            rules={[{ required: true, message: '请选择种子' }]}
          >
            <Select
              placeholder="请选择相关种子"
              showSearch
              filterOption={(input, option) =>
                String(option?.children || '').toLowerCase().indexOf(input.toLowerCase()) >= 0
              }
            >
              {torrents.map(torrent => (
                <Option key={torrent.id} value={torrent.id}>
                  {torrent.title}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" loading={submitting}>
                确认完成
              </Button>
              <Button onClick={() => setFillModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default RequestDetail; 